//
//  NSString+DKPublic.m
//  DanKU
//
//  Created by 吴斌 on 2023/10/1.
//

#import "NSString+DKPublic.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/ASIdentifierManager.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import <sys/sysctl.h>
#import <mach/mach.h>


#import <SystemConfiguration/SystemConfiguration.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netinet/in.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <sys/utsname.h>
#import <net/if_dl.h>
#import <net/if.h>
#import "AFNetworking/AFNetworking.h"
@implementation NSString (DKPublic)
+ (NSString *)getServiceUrl:(NSString *)endServiceUrl{
    return [NSString stringWithFormat:@"%@%@",DK_ServiceUrl,endServiceUrl];
}

+ (CGSize)getContentSize:(NSString *)content withFont:(UIFont *)contentFont withSize:(CGSize)maxSize{
    NSDictionary *attributes = @{NSFontAttributeName:contentFont};
    //计算出文字的宽度
    CGSize textSize = [content boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil].size;
    return textSize;
}

+ (CGSize)getContentAttributedSize:(NSAttributedString *)content withSize:(CGSize)maxSize{
    //计算出文字的宽度
    CGSize textSize = [content boundingRectWithSize:maxSize options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) context:nil].size;
    return textSize;
}
//时间戳转时间
+ (NSString *)timeWithDayMonYear:(NSString *)timestamp{
    // 时间戳转日期
    NSTimeInterval timeInterval = [timestamp doubleValue]/1000;
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 实例化一个NSDateFormatter对象，设定时间格式，这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *dateStr = [dateFormatter stringFromDate:detailDate];
    return dateStr;
}
//金额显示
+ (NSString *)makeShowMoney:(NSString *)moneyCoin{
    //金额为0，直接显示
    if([moneyCoin isEqualToString:@"0"]||moneyCoin.length == 0){
        return moneyCoin;
    }
    //金额整数，每三位添加，
    if(![moneyCoin containsString:@"."]){
        return [self makeStringFormatToThreeBit:moneyCoin];
    }else{//金额不是整数，每三位添加，保留两位小数
        NSArray *moneyCoins = [moneyCoin componentsSeparatedByString:@"."];
        if(moneyCoins.count > 2){
            return moneyCoin;
        }else if (moneyCoins.count == 2){
            NSString *point = [NSString stringWithFormat:@"%2@",moneyCoins.lastObject];
            return [NSString stringWithFormat:@"%@.%@",[self makeStringFormatToThreeBit:moneyCoins.firstObject],point];
        }else{
            return [self makeStringFormatToThreeBit:moneyCoin];
        }
    }
}
//三位添加，
+ (NSString *)makeStringFormatToThreeBit:(NSString *)string{
    NSString * tempString = [string stringByReplacingOccurrencesOfString:@","withString:@""];
    NSMutableString * mutableString = [NSMutableString stringWithString:tempString];
    NSInteger n = 2;
    for(NSInteger i = tempString.length - 3; i > 0; i--) {
        n++;
        if(n == 3) {
            [mutableString insertString:@"," atIndex:i];
            n = 0;
        }
    }
    return mutableString;
}
//图片压缩大小
+ (NSData *)changeImageSizeForData:(UIImage *)image toByte:(NSUInteger)maxByte{
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxByte) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression) ;
        if (data.length < maxByte * 0.9) {
            min = compression;
        } else if (data.length > maxByte) {
            max= compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxByte) return data;
    NSUInteger temLength = 0;
    while (data.length > maxByte && data.length != temLength) {
        temLength = data.length;
        CGFloat ratio = (CGFloat)maxByte / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),(NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect: CGRectMake(0, 0, 100, 100)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    return data;
    
}
//base64解码
+ (UIImage *)imageWithBase64String:(NSString *)base64String {
    if (base64String.length) {
        if ([base64String containsString:@"data:image/png;base64"]) {
            base64String = [base64String componentsSeparatedByString:@"data:image/png;base64"].lastObject;
        }
        NSData *baseImg = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
        return [UIImage imageWithData:baseImg];
    }
    return nil;
}
//验证邮箱格式
+ (BOOL)makeEmailAddress:(NSString *)emailAddress{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *email = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [email evaluateWithObject:emailAddress];
}
//消息
//是否是当天时间
+ (BOOL)isCurrentDayTime{
    //一天之内只提示一次
    //    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    //拿到当前时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //当前时间
    NSDate *nowDate = [NSDate date];
    NSString *nowDateStr= [dateFormatter stringFromDate:nowDate];
    //之前时间
    NSString *saveNowDate = [NSString stringWithFormat:@"%@%@",NSUserDefault_SaveNowDate,[DKGlobalHelper defaultManager].registerUserMdl.phone];
    NSString *agoDateStr = DK_GETObject_USERDEF(saveNowDate);
    //判断时间差
    if ([agoDateStr isEqualToString:nowDateStr]) {
        return YES;
    }else{
        //弹窗，这里写你的弹窗代码逻辑
        //保存当前时间
        DK_SETObject_USERDEF(saveNowDate, nowDateStr);
        return NO;
    }
}
//获得档期时间戳
+ (NSString *)getCurrentTimeTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"];
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone systemTimeZone];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = @"";
    timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
    return timeSp;
}
//获得档期时间戳天数
+ (NSString *)getCurrentTimeDayTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    //当前时间
    NSDate *nowDate = [NSDate date];
    NSString *nowDateStr = [formatter stringFromDate:nowDate];
    return nowDateStr;
}
+ (NSString *)getIdfa {
    __block NSString *idfa = @"";
    if (@available(iOS 14, *)) {
        // iOS14及以上版本需要先请求权限
        [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
            // 获取到权限后，依然使用老方法获取idfa
            if (status == ATTrackingManagerAuthorizationStatusAuthorized) {
                idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
            } else {
                
            }
        }];
    } else {
        // iOS14以下版本依然使用老方法
        // 判断在设置-隐私里用户是否打开了广告跟踪
        if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
            idfa = [[ASIdentifierManager sharedManager].advertisingIdentifier UUIDString];
        } else {
        }
    }
    return idfa;
}
//生成自己的uuid
+ (NSString *)getSelfUuid{
    CFUUIDRef uuidref = CFUUIDCreate(kCFAllocatorDefault);
    
    CFStringRef uuid_string_ref = CFUUIDCreateString(kCFAllocatorDefault, uuidref);
    
    CFRelease(uuidref);
    
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];

    CFRelease(uuid_string_ref);
    return uuid;
}
+ (NSString *)getNetworkIPAddress {
    NSString *address = nil;
    
    struct ifaddrs *interfaces = NULL;
    
    struct ifaddrs *temp_addr = NULL;
    
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) {
        
        // Loop through linked list of interfaces
        
        temp_addr = interfaces;
        
        while(temp_addr != NULL) {
            
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                
                // Check if interface is en0 which is the wifi connection on the iPhone
                
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    
                    // Get NSString from C String
                    
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    
                }
                
            }
            
            temp_addr = temp_addr->ifa_next;
            
        }
        
    }
    
    // Free memory
    
    freeifaddrs(interfaces);
    
    return address;
}
//获取设备的总容量
+ (NSString *)totalDiskSpace{
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    NSNumber *number = [fattributes objectForKey:NSFileSystemSize];
    return number.description;
}
//可用容量
+ (NSString *)freeDiskSpace{
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    NSNumber *number = [fattributes objectForKey:NSFileSystemFreeSize];
    return number.description;
}
//获取屏幕分辨率
+ (NSString *)getScreenRate{
    float scaleFactor = [[UIScreen mainScreen] scale];
    CGRect screen = [[UIScreen mainScreen] bounds];
    int widthInPixel = screen.size.width * scaleFactor;
    int heightInPixel = screen.size.height * scaleFactor;
    return [NSString stringWithFormat:@"%dx%d",widthInPixel,heightInPixel];
}
//获取是否是wifi
+ (NSString *)isWifiNetStatus{
    RealReachability *reachability  = [RealReachability sharedInstance];
    ReachabilityStatus  status  =  [reachability currentReachabilityStatus];
    if(status == RealStatusViaWiFi){
        return @"1";
    }else{
        return @"0";
    }
}
+ (NSString *)getWifiSSID{
    NSString *ssid = nil;
    CFArrayRef arrRef = CNCopySupportedInterfaces();
    NSArray *ifs = (__bridge id)arrRef;
    for (NSString *ifnam in ifs) {
        CFDictionaryRef dicRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSDictionary *info = (__bridge id)dicRef;
        if (info[@"BSSID"]) {
            ssid = info[@"SSID"];
        }
        if(dicRef !=nil) {
            CFRelease(dicRef);
        }
    }
    if(arrRef != nil) {
        CFRelease(arrRef);
    }
    return ssid;
}
//获取总内存大小
+ (NSString *)getTotalMemorySize{
    return [NSString stringWithFormat:@"%llu",[NSProcessInfo processInfo].physicalMemory];
}
//获取可用内存大小(kb)
+(long)getAvailableMemorySize{
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmStats, &infoCount);
    if(kernReturn != KERN_SUCCESS){
        return NSNotFound;
    }
    return((vm_page_size * vmStats.free_count + vm_page_size * vmStats.inactive_count))*1024;
}
+ (NSDate *)getThreeYearTime{
    NSDate * mydate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSLog(@"---当前的时间的字符串 =%@",currentDateStr);
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:-3];
    [adcomps setMonth:0];
    [adcomps setDay:0];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    NSLog(@"---前三年 =%@",beforDate);
    return newdate;
}
+ (NSDate *)getOneYearTime{
    NSDate * mydate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    NSLog(@"---当前的时间的字符串 =%@",currentDateStr);
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:+1];
    [adcomps setMonth:0];
    [adcomps setDay:0];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    NSLog(@"---后一年 =%@",beforDate);
    return newdate;
}
+ (NSString *)dicChangeString:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
+ (NSDictionary *)stringChangeDic:(NSString *)json{
    NSString * jsonString = json;
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers error:&error];
    return dic;
}
#pragma mark -- app信息
+ (NSString *)getAppVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}
#pragma  mark  device_info[general_data] 设备基本信息
//系统开机时间
+ (int)getSystemUptimeByMillSecond{
    const int64_t kOneMillion = 1000*1000;
    static mach_timebase_info_data_t s_timebase_info;
    if (s_timebase_info.denom == 0) {
        (void) mach_timebase_info(&s_timebase_info);
    }
    return (int)(mach_absolute_time()*s_timebase_info.numer)/(kOneMillion*s_timebase_info.denom);
}
//是否设置代理
+ (BOOL)getProxyStatus {
    NSDictionary *proxySettings = NSMakeCollectable([(NSDictionary *)CFNetworkCopySystemProxySettings() autorelease]);

    NSArray *proxies = NSMakeCollectable([(NSArray *)CFNetworkCopyProxiesForURL((CFURLRef)[NSURL URLWithString:@"http://www.baidu.com"], (CFDictionaryRef)proxySettings) autorelease]);
    NSDictionary *settings = [proxies objectAtIndex:0];

    NSLog(@"host=%@", [settings objectForKey:(NSString *)kCFProxyHostNameKey]);
    NSLog(@"port=%@", [settings objectForKey:(NSString *)kCFProxyPortNumberKey]);
    NSLog(@"type=%@", [settings objectForKey:(NSString *)kCFProxyTypeKey]);

    if ([[settings objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:@"kCFProxyTypeNone"]) {
        //没有设置代理
        return NO;
    } else {
        //设置代理了
        return YES;
    }
}
//是否使用vpn
+ (BOOL)isVPNOn{
   BOOL flag = NO;
   NSString *version = [UIDevice currentDevice].systemVersion;
   // need two ways to judge this.
   if (version.doubleValue >= 9.0)
   {
       NSDictionary *dict = CFBridgingRelease(CFNetworkCopySystemProxySettings());
       NSArray *keys = [dict[@"__SCOPED__"] allKeys];
       for (NSString *key in keys) {
           if ([key rangeOfString:@"tap"].location != NSNotFound ||
               [key rangeOfString:@"tun"].location != NSNotFound ||
               [key rangeOfString:@"ipsec"].location != NSNotFound ||
               [key rangeOfString:@"ppp"].location != NSNotFound){
               flag = YES;
               break;
           }
       }
   }
   else
   {
       struct ifaddrs *interfaces = NULL;
       struct ifaddrs *temp_addr = NULL;
       int success = 0;
       
       // retrieve the current interfaces - returns 0 on success
       success = getifaddrs(&interfaces);
       if (success == 0)
       {
           // Loop through linked list of interfaces
           temp_addr = interfaces;
           while (temp_addr != NULL)
           {
               NSString *string = [NSString stringWithFormat:@"%s" , temp_addr->ifa_name];
               if ([string rangeOfString:@"tap"].location != NSNotFound ||
                   [string rangeOfString:@"tun"].location != NSNotFound ||
                   [string rangeOfString:@"ipsec"].location != NSNotFound ||
                   [string rangeOfString:@"ppp"].location != NSNotFound)
               {
                   flag = YES;
                   break;
               }
               temp_addr = temp_addr->ifa_next;
           }
       }
       
       // Free memory
       freeifaddrs(interfaces);
   }


   return flag;
}
//运营商无线接入技术
+ (NSString *)networkInfo{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [info subscriberCellularProvider];
    NSString *mcc = [carrier mobileCountryCode]; // 国家码 如：460
    NSString *mnc = [carrier mobileNetworkCode]; // 网络码 如：01
    NSString *name = [carrier carrierName]; // 运营商名称，中国联通
    NSString *isoCountryCode = [carrier isoCountryCode]; // cn
    BOOL allowsVOIP = [carrier allowsVOIP];// YES
    NSString *radioAccessTechnology = info.currentRadioAccessTechnology; // 无线连接技术，如CTRadioAccessTechnologyLTE
    if(!radioAccessTechnology){
        radioAccessTechnology = @"";
    }
    return radioAccessTechnology;
}
#pragma  mark  device_info[new_storage] 存储信息
+ (NSString *)totalMemoryString {
    return [NSString stringWithFormat:@"%llu", [self totalMemory]];
}

+ (NSString *)freeMemoryString {
    return [NSString stringWithFormat:@"%llu", [self freeMemory]];
}

+ (NSString *)purgeableMemoryString {
    return [NSString stringWithFormat:@"%llu", [self purgeableMemory]];
}

+ (NSString *)inactiveMemoryString {
    return [NSString stringWithFormat:@"%llu", [self inactiveMemory]];
}

+ (NSString *)activeMemoryString {
    return [NSString stringWithFormat:@"%llu", [self activeMemory]];
}

+ (NSString *)wiredMemoryString {
    return [NSString stringWithFormat:@"%llu", [self wiredMemory]];
}

+ (NSString *)usedMemoryString {
    return [NSString stringWithFormat:@"%llu", [self usedMemory]];
}

+ (unsigned long long)totalMemory {
    return [NSProcessInfo processInfo].physicalMemory;
}

+ (unsigned long long)freeMemory {
    vm_statistics64_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO64_COUNT;
    kern_return_t kernReturn = host_statistics64(mach_host_self(),
                                                 HOST_VM_INFO64,
                                                 (host_info64_t)&vmStats,
                                                 &infoCount);

    if (kernReturn != KERN_SUCCESS) {
        return 0; // Failed to get information
    }

    return vm_page_size * vmStats.free_count;
}

+ (unsigned long long)purgeableMemory {
    vm_statistics64_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO64_COUNT;
    kern_return_t kernReturn = host_statistics64(mach_host_self(),
                                                 HOST_VM_INFO64,
                                                 (host_info64_t)&vmStats,
                                                 &infoCount);

    if (kernReturn != KERN_SUCCESS) {
        return 0; // Failed to get information
    }

    return vm_page_size * vmStats.purgeable_count;
}

+ (unsigned long long)inactiveMemory {
    vm_statistics64_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO64_COUNT;
    kern_return_t kernReturn = host_statistics64(mach_host_self(),
                                                 HOST_VM_INFO64,
                                                 (host_info64_t)&vmStats,
                                                 &infoCount);

    if (kernReturn != KERN_SUCCESS) {
        return 0; // Failed to get information
    }

    return vm_page_size * vmStats.inactive_count;
}

+ (unsigned long long)activeMemory {
    vm_statistics64_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO64_COUNT;
    kern_return_t kernReturn = host_statistics64(mach_host_self(),
                                                 HOST_VM_INFO64,
                                                 (host_info64_t)&vmStats,
                                                 &infoCount);

    if (kernReturn != KERN_SUCCESS) {
        return 0; // Failed to get information
    }

    return vm_page_size * vmStats.active_count;
}

+ (unsigned long long)wiredMemory {
    vm_statistics64_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO64_COUNT;
    kern_return_t kernReturn = host_statistics64(mach_host_self(),
                                                 HOST_VM_INFO64,
                                                 (host_info64_t)&vmStats,
                                                 &infoCount);

    if (kernReturn != KERN_SUCCESS) {
        return 0; // Failed to get information
    }

    return vm_page_size * vmStats.wire_count;
}

+ (unsigned long long)usedMemory {
    return [self totalMemory] - [self freeMemory] - [self purgeableMemory];
}

#pragma  mark  device_info[battery_status] 电量信息
+ (float)batteryLevel {
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    return device.batteryLevel * 100;
}

+ (UIDeviceBatteryState)batteryState {
    UIDevice *device = [UIDevice currentDevice];
    device.batteryMonitoringEnabled = YES;
    return device.batteryState;
}

+ (NSString *)batteryStateString:(UIDeviceBatteryState)batteryState {
    switch (batteryState) {
        case UIDeviceBatteryStateUnknown:
            return @"Unknown";
        case UIDeviceBatteryStateUnplugged:
            return @"Unplugged";
        case UIDeviceBatteryStateCharging:
            return @"Charging";
        case UIDeviceBatteryStateFull:
            return @"Full";
        default:
            return @"Unknown";
    }
}

+ (NSString *)currentDeviceTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}

+ (NSTimeInterval)uptimeInMillisecondsIncludingSleep {
    return NSProcessInfo.processInfo.systemUptime * 1000;
}

+ (NSString *)macAddress {
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;

    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;

    if ((mib[5] = if_nametoindex("en0")) == 0) {
        return @"02:00:00:00:00:00";
    }

    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        return @"02:00:00:00:00:00";
    }

    if ((buf = malloc(len)) == NULL) {
        return @"02:00:00:00:00:00";
    }

    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        free(buf);
        return @"02:00:00:00:00:00";
    }

    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);

    NSString *macAddress = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                                                      ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]];
    free(buf);

    return macAddress;
}

+ (BOOL)isUsingProxy {
    NSDictionary *proxySettings = CFBridgingRelease(CFNetworkCopySystemProxySettings());
    NSArray *proxies = CFBridgingRelease(CFNetworkCopyProxiesForURL((__bridge CFURLRef)[NSURL URLWithString:@"https://www.apple.com"], (__bridge CFDictionaryRef)(proxySettings)));

    for (NSDictionary *proxy in proxies) {
        if ([[proxy objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:(NSString *)kCFProxyTypeHTTP] ||
            [[proxy objectForKey:(NSString *)kCFProxyTypeKey] isEqualToString:(NSString *)kCFProxyTypeHTTPS]) {
            return YES;
        }
    }

    return NO;
}

+ (BOOL)isUsingVPN {
    NSArray *interfaceNames = CFBridgingRelease(CFNetworkCopyProxiesForURL((__bridge CFURLRef)[NSURL URLWithString:@"https://www.apple.com"], NULL));

    for (NSString *interfaceName in interfaceNames) {
        if ([interfaceName isEqualToString:@"utun0"] || [interfaceName isEqualToString:@"utun1"] || [interfaceName isEqualToString:@"utun2"]) {
            return YES;
        }
    }

    return NO;
}

+ (NSString *)carrierTechnology {
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    NSString *mConnectType = [[NSString alloc] initWithFormat:@"%@",info.currentRadioAccessTechnology];
    if(!mConnectType.length||[mConnectType isEqual:[NSNull null]]||[mConnectType isEqualToString:@"(null)"]){
        mConnectType = @"";
    }
    return mConnectType;
//    CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init];
//    NSString *currentRadioAccessTechnology = info.dataServiceIdentifier;
//    if (@available(iOS 12.1, *)) {
//        if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
//            NSDictionary *radioDic = [info serviceSubscriberCellularProviders];
//            if (radioDic.allKeys.count) {
//                currentRadioAccessTechnology = [radioDic objectForKey:radioDic.allKeys[0]];
//            }
//        }
//        if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
//            NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
//            if (radioDic.allKeys.count) {
//                currentRadioAccessTechnology = [radioDic objectForKey:radioDic.allKeys[0]];
//            }
//        }
//    }else{
//        currentRadioAccessTechnology = [info currentRadioAccessTechnology];
//    }
//    return currentRadioAccessTechnology;
    
//    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
//
//    if (@available(iOS 12.0, *)) {
//        NSDictionary *serviceCurrentRadioAccessTechnology = networkInfo.serviceCurrentRadioAccessTechnology;
//        NSString *primaryService = networkInfo.serviceCurrentRadioAccessTechnology.allKeys.firstObject;
//
//        return serviceCurrentRadioAccessTechnology[primaryService];
//    } else {
//        return networkInfo.serviceCurrentRadioAccessTechnology;
//    }
}

+ (NSString *)networkType {
    NSString *netconnType = @"";
    // 创建零地址，0.0.0.0的地址表示查询本机的网络连接状态
    struct sockaddr_storage zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.ss_len = sizeof(zeroAddress);
    zeroAddress.ss_family = AF_INET;
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    // 获得连接的标志
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    // 如果不能获取连接标志，则不能连接网络，直接返回
    if (!didRetrieveFlags) {
        return @"none";
    }
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    if (isReachable && !needsConnection) {
    }else{
        return @"none";
    }
    if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == kSCNetworkReachabilityFlagsConnectionRequired ) {
        return @"none";
    } else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
        return [self cellularType];
    } else {
        return @"WiFi";
    }
}
+ (NSString *)cellularType {
    CTTelephonyNetworkInfo * info = [[CTTelephonyNetworkInfo alloc] init];
    NSString *currentRadioAccessTechnology;
    if (@available(iOS 12.1, *)) {
        if (info && [info respondsToSelector:@selector(serviceCurrentRadioAccessTechnology)]) {
            NSDictionary *radioDic = [info serviceCurrentRadioAccessTechnology];
            if (radioDic.allKeys.count) {
                currentRadioAccessTechnology = [radioDic objectForKey:radioDic.allKeys [0]];
            } else {
                return @"none";;
            }
        } else {
            return @"none";;
        }
    } else {
        currentRadioAccessTechnology = info.currentRadioAccessTechnology;
    }
    if (currentRadioAccessTechnology) {
        if (@available(iOS 14.1, *)) {
            if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNRNSA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNR]) {
                return @"5G";
            }
        }
        if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
            return @"4G";
        } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
            return @"3G";
        } else if ([currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] || [currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
            return @"2G";
        } else {
            return @"Unknow";
        }
    } else {
        return @"none";;
    }
}
+ (NSString *)timeZoneID {
    return [NSTimeZone localTimeZone].abbreviation;
}

+ (NSTimeInterval)uptimeInMillisecondsExcludingSleep {
    struct timeval boottime;
    int mib[2] = {CTL_KERN, KERN_BOOTTIME};

    if (sysctl(mib, 2, &boottime, &(size_t){sizeof(boottime)}, NULL, 0) != -1) {
        struct timeval now;
        gettimeofday(&now, NULL);

        return (now.tv_sec - boottime.tv_sec) * 1000.0 + (now.tv_usec - boottime.tv_usec) / 1000.0;
    }

    return 0;
}

+ (NSString *)uniqueIdentifier {
    struct utsname systemInfo;
    uname(&systemInfo);

    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    NSString *uniqueIdentifier = [NSString stringWithFormat:@"%@%@", deviceModel, NSUUID.UUID.UUIDString];

    return uniqueIdentifier;
}



+ (NSUInteger)activeProcessCount {
    return [NSProcessInfo processInfo].activeProcessorCount;
//    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
//    size_t miblen = 4;
//
//    struct kinfo_proc *procs = NULL;
//    size_t size;
//
//    // Get initial size
//    if (sysctl(mib, miblen, NULL, &size, NULL, 0) < 0) {
//        return NSNotFound;
//    }
//
//    // Allocate memory for process information
//    procs = malloc(size);
//
//    // Get actual process information
//    if (sysctl(mib, miblen, procs, &size, NULL, 0) < 0) {
//        free(procs);
//        return NSNotFound;
//    }
//
//    // Calculate the number of processes
//    NSUInteger processCount = size / sizeof(struct kinfo_proc);
//
//    // Free allocated memory
//    free(procs);
//
//    return processCount;
}
+ (NSString *)processName{
    return [NSProcessInfo processInfo].processName;
}
+ (NSString *)processEnvironment{
    return [NSProcessInfo processInfo].environment.mj_JSONString;
}
+ (NSString *)processArguments{
    return [NSProcessInfo processInfo].arguments.mj_JSONString;
}
+ (NSArray<NSString *> *)activeProcessNames {
    NSMutableArray<NSString *> *processNames = [NSMutableArray array];

    int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
    size_t miblen = 4;

    struct kinfo_proc *procs = NULL;
    size_t size;

    // Get initial size
    if (sysctl(mib, miblen, NULL, &size, NULL, 0) < 0) {
        return processNames;
    }

    // Allocate memory for process information
    procs = malloc(size);

    // Get actual process information
    if (sysctl(mib, miblen, procs, &size, NULL, 0) < 0) {
        free(procs);
        return processNames;
    }

    // Iterate through processes and add names to the array
    for (NSUInteger i = 0; i < size / sizeof(struct kinfo_proc); i++) {
        NSString *processName = [NSString stringWithUTF8String:procs[i].kp_proc.p_comm];
        [processNames addObject:processName];
    }

    // Free allocated memory
    free(procs);

    return processNames;
}

+ (NSUInteger)physicalMemory {
    return (NSUInteger)[NSProcessInfo processInfo].physicalMemory;
}

+ (NSUInteger)processCount {
    return (NSUInteger)[NSProcessInfo processInfo].processorCount;
}

+ (pid_t)processID {
    return (pid_t)[NSProcessInfo processInfo].processIdentifier;
}

+ (NSString *)operatingEnvironment {
    return [NSString stringWithCString:getenv("XPC_SERVICE_NAME") encoding:NSUTF8StringEncoding];
}

+ (NSString *)operatingSystemString {
//    size_t size;
//    sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
//
//    char *version = malloc(size);
//    sysctlbyname("kern.osversion", version, &size, NULL, 0);
//
//    NSString *osVersion = [NSString stringWithUTF8String:version];
//    free(version);
//
//    return osVersion;
    NSString *osName = [[UIDevice currentDevice] systemName];
    NSString *osVersion = [[UIDevice currentDevice] systemVersion];
    NSString *osString = [NSString stringWithFormat:@"Version %@",osVersion];
    return osString;
}

+ (NSTimeInterval)systemUptime {
    struct timeval boottime;
    int mib[2] = {CTL_KERN, KERN_BOOTTIME};
    
    if (sysctl(mib, 2, &boottime, &(size_t){sizeof(boottime)}, NULL, 0) != -1) {
        struct timeval now;
        gettimeofday(&now, NULL);
        
        return now.tv_sec - boottime.tv_sec;
    }
    
    return 0;
}

+ (BOOL)isLowPowerModeEnabled {
    return [NSProcessInfo processInfo].isLowPowerModeEnabled;
}


+ (NSInteger)screenHeight {
    return (NSInteger)[UIScreen mainScreen].bounds.size.height;
}

+ (NSString *)deviceName {
    return [UIDevice currentDevice].name;
}

+ (NSInteger)screenWidth {
    return (NSInteger)[UIScreen mainScreen].bounds.size.width;
}

+ (NSString *)deviceModel {
    NSString *deviceModel = [[UIDevice currentDevice] model];
    return deviceModel;
//    struct utsname systemInfo;
//    uname(&systemInfo);
//    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}
+ (NSString *)sysModelName {
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    ///iPhone
    ///https://everymac.com/systems/apple/iphone/index-iphone-specs.html
    if ([deviceModel isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceModel isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceModel isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    if ([deviceModel isEqualToString:@"iPhone5,3"])    return @"iPhone 5c";
    if ([deviceModel isEqualToString:@"iPhone5,4"])    return @"iPhone 5c";
    if ([deviceModel isEqualToString:@"iPhone6,1"])    return @"iPhone 5s";
    if ([deviceModel isEqualToString:@"iPhone6,2"])    return @"iPhone 5s";
    if ([deviceModel isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceModel isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceModel isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceModel isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceModel isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([deviceModel isEqualToString:@"iPhone9,1"])    return @"iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone9,3"])    return @"iPhone 7";
    if ([deviceModel isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus";
    if ([deviceModel isEqualToString:@"iPhone10,1"])   return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,4"])   return @"iPhone_8";
    if ([deviceModel isEqualToString:@"iPhone10,2"])   return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,5"])   return @"iPhone_8_Plus";
    if ([deviceModel isEqualToString:@"iPhone10,3"])   return @"iPhone X";
    if ([deviceModel isEqualToString:@"iPhone10,6"])   return @"iPhone X";
    if ([deviceModel isEqualToString:@"iPhone11,2"])   return @"iPhone XS";
    if ([deviceModel isEqualToString:@"iPhone11,4"])   return @"iPhone XS MAX";
    if ([deviceModel isEqualToString:@"iPhone11,6"])   return @"iPhone XS MAX";
    if ([deviceModel isEqualToString:@"iPhone11,8"])   return @"iPhone XR";
    if ([deviceModel isEqualToString:@"iPhone12,1"])   return @"iPhone 11";
    if ([deviceModel isEqualToString:@"iPhone12,3"])   return @"iPhone 11 Pro";
    if ([deviceModel isEqualToString:@"iPhone12,5"])   return @"iPhone 11 Pro Max";
    if ([deviceModel isEqualToString:@"iPhone12,8"])   return @"iPhone SE 2";
    if ([deviceModel isEqualToString:@"iPhone13,1"])   return @"iPhone 12 mini";
    if ([deviceModel isEqualToString:@"iPhone13,2"])   return @"iPhone 12";
    if ([deviceModel isEqualToString:@"iPhone13,3"])   return @"iPhone 12 Pro";
    if ([deviceModel isEqualToString:@"iPhone13,4"])   return @"iPhone 12 Pro Max";
    if ([deviceModel isEqualToString:@"iPhone14,4"])   return @"iPhone 13 mini";
    if ([deviceModel isEqualToString:@"iPhone14,5"])   return @"iPhone 13";
    if ([deviceModel isEqualToString:@"iPhone14,2"])   return @"iPhone 13 Pro";
    if ([deviceModel isEqualToString:@"iPhone14,3"])   return @"iPhone 13 Pro Max";
    if ([deviceModel isEqualToString:@"iPhone14,6"])   return @"iPhone SE 3";
    if ([deviceModel isEqualToString:@"iPhone14,7"])   return @"iPhone 14";
    if ([deviceModel isEqualToString:@"iPhone14,8"])   return @"iPhone 14 Plus";
    if ([deviceModel isEqualToString:@"iPhone15,2"])   return @"iPhone 14 Pro";
    if ([deviceModel isEqualToString:@"iPhone15,3"])   return @"iPhone 14 Pro Max";
    if ([deviceModel isEqualToString:@"iPhone15,4"])   return @"iPhone 15";
    if ([deviceModel isEqualToString:@"iPhone15,5"])   return @"iPhone 15 Plus";
    if ([deviceModel isEqualToString:@"iPhone16,1"])   return @"iPhone 15 Pro";
    if ([deviceModel isEqualToString:@"iPhone16,2"])   return @"iPhone 15 Pro Max";
    
    ///iPod
    ///https://everymac.com/systems/apple/ipod/index-ipod-specs.html
    if ([deviceModel isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceModel isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceModel isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceModel isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceModel isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";
    
    ///iPad
   ///https://everymac.com/systems/apple/ipad/index-ipad-specs.html
    if ([deviceModel isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceModel isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    if ([deviceModel isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceModel isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([deviceModel isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([deviceModel isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    if ([deviceModel isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([deviceModel isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([deviceModel isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    if ([deviceModel isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    if ([deviceModel isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
    if ([deviceModel isEqualToString:@"iPad4,4"])      return @"iPad Mini 2 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad4,5"])      return @"iPad Mini 2 (Cellular)";
    if ([deviceModel isEqualToString:@"iPad4,6"])      return @"iPad Mini 2";
    if ([deviceModel isEqualToString:@"iPad4,7"])      return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,8"])      return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad4,9"])      return @"iPad Mini 3";
    if ([deviceModel isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
    if ([deviceModel isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (LTE)";
    if ([deviceModel isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    if ([deviceModel isEqualToString:@"iPad6,3"])      return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,4"])      return @"iPad Pro 9.7";
    if ([deviceModel isEqualToString:@"iPad6,7"])      return @"iPad Pro 12.9";
    if ([deviceModel isEqualToString:@"iPad6,8"])      return @"iPad Pro 12.9";

    if ([deviceModel isEqualToString:@"AppleTV2,1"])      return @"Apple TV 2";
    if ([deviceModel isEqualToString:@"AppleTV3,1"])      return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV3,2"])      return @"Apple TV 3";
    if ([deviceModel isEqualToString:@"AppleTV5,3"])      return @"Apple TV 4";

    if ([deviceModel isEqualToString:@"i386"] || [deviceModel isEqualToString:@"x86_64"]) {
        // 模拟器的名称默认就是型号的名称
        return [NSString stringWithFormat:@"%@ Simulator",UIDevice.currentDevice.name];
    }

    return deviceModel;
}
+ (CGFloat)physicalSize {
    return (CGFloat)([[UIScreen mainScreen] bounds].size.width / (CGFloat)[[UIScreen mainScreen] scale]);
}

+ (NSString *)systemVersion {
    return [UIDevice currentDevice].systemVersion;
}

+ (NSInteger)signalStrength {
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    NSNumber *signalStrength = networkInfo.serviceCurrentRadioAccessTechnology.allValues.firstObject;
    return signalStrength ? [signalStrength integerValue] : -1;
}

+ (NSString *)keyboardType {
    return [UIDevice currentDevice].model;
}

+ (BOOL)isSimulator {
    return TARGET_OS_SIMULATOR != 0;
}
//获取随机数
+ (NSString *)getRandomStringWithNum:(NSInteger)num
{
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < num; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}
@end
